﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace FySystem.Configuration
{
    public class JsonAppSettings
    {
        private static string FILE_NAME = AppDomain.CurrentDomain.BaseDirectory + "appsettings.json";
        internal static JsonElement ROOT_ELEMENT;

        /// <summary>
        /// 构造函数，初始化值，从文件中获取数据
        /// </summary>
        internal JsonAppSettings()
        {
            try
            {
                if (File.Exists(FILE_NAME) == false)
                    return;

                StringBuilder sb = new StringBuilder();
                using(FileStream fs=new FileStream(FILE_NAME, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    using(StreamReader sr=new StreamReader(fs))
                    {
                        while (sr.Peek() != -1)
                            sb.Append(sr.ReadLine());
                    }
                }
                JsonDocument jsonDoc = JsonDocument.Parse(sb.ToString());
                ROOT_ELEMENT = jsonDoc.RootElement;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 简易方式获取值，仅针对key-value的设置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string this[string key]
        {
            get
            {
                string res = string.Empty;
                try
                {
                    JsonElement je;
                    if (ROOT_ELEMENT.TryGetProperty(key, out je) == false)
                        throw new Exception("设置键值不存在~");

                    res = je.GetString();
                }
                catch (Exception)
                {
                    throw;
                }
                return res;
            }
        }

        /// <summary>
        /// 复杂方式获取，如果key对应的value是一个json对象或者json数组，就只能用这种方式
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public JsonElement GetJson(string key)
        {
            JsonElement res;
            try
            {
                if (ROOT_ELEMENT.TryGetProperty(key, out res) == false)
                    throw new Exception("设置键值不存在~");
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }
    }
}
